import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15

// 导入页面组件
import "pages" as Pages
import "dialogs"

ApplicationWindow {
    id: mainWindow
    visible: true
    width: 1280
    height: 800
    minimumWidth: 1024
    minimumHeight: 600
    title: "Modbus TCP 监控系统 - v1.0.0"
    visibility: Window.Maximized
    
    // ========================================
    // 全局属性
    // ========================================
    property string currentPage: "dashboard"
    property bool drawerOpen: true
    
    // 主题颜色
    readonly property color primaryColor: "#3b82f6"
    readonly property color secondaryColor: "#10b981"
    readonly property color dangerColor: "#ef4444"
    readonly property color warningColor: "#f59e0b"
    readonly property color backgroundColor: "#f5f5f5"
    readonly property color sidebarColor: "#2c3e50"
    
    // ========================================
    // 主布局：侧边栏 + 内容区
    // ========================================
    RowLayout {
        anchors.fill: parent
        spacing: 0
        
        // ========================================
        // 左侧导航栏（侧边栏）
        // ========================================
        Rectangle {
            id: sidebar
            Layout.fillHeight: true
            Layout.preferredWidth: drawerOpen ? 220 : 0
            visible: drawerOpen
            color: sidebarColor
            
            Behavior on Layout.preferredWidth {
                NumberAnimation { duration: 300; easing.type: Easing.InOutQuad }
            }
            
            ColumnLayout {
                anchors.fill: parent
                spacing: 0
                
                // 系统标题区
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 80
                    color: Qt.rgba(0, 0, 0, 0.2)
                    
                    ColumnLayout {
                        anchors.centerIn: parent
                        spacing: 5
                        
                        RowLayout {
                            Layout.alignment: Qt.AlignHCenter
                            spacing: 10
                            
                            Text {
                                text: "🏭"
                                font.pixelSize: 24
                            }
                            
                            Text {
                                text: "Modbus TCP 监控"
                                font.pixelSize: 18
                                font.bold: true
                                color: "white"
                            }
                        }
                        
                        Text {
                            text: "工业设备实时监控系统"
                            font.pixelSize: 11
                            color: Qt.rgba(255, 255, 255, 0.7)
                            Layout.alignment: Qt.AlignHCenter
                        }
                    }
                }
                
                // 导航菜单区
                ScrollView {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    
                    ColumnLayout {
                        width: sidebar.width
                        spacing: 5
                        
                        Item { height: 10 } // 顶部间距
                        
                        // 菜单项：仪表盘
                        NavMenuItem {
                            icon: "📊"
                            text: "仪表盘"
                            pageId: "dashboard"
                            active: currentPage === "dashboard"
                            onClicked: switchToPage("dashboard")
                        }
                        
                        // 菜单项：设备管理
                        NavMenuItem {
                            icon: "⚙️"
                            text: "设备管理"
                            pageId: "device"
                            active: currentPage === "device"
                            onClicked: switchToPage("device")
                        }
                        
                        // 菜单项：历史数据
                        NavMenuItem {
                            icon: "📈"
                            text: "历史数据"
                            pageId: "history"
                            active: currentPage === "history"
                            onClicked: switchToPage("history")
                        }
                        
                        // 菜单项：报警管理
                        NavMenuItem {
                            icon: "🚨"
                            text: "报警管理"
                            pageId: "alarm"
                            active: currentPage === "alarm"
                            onClicked: switchToPage("alarm")
                        }
                        
                        // 分隔线
                        Rectangle {
                            Layout.fillWidth: true
                            Layout.preferredHeight: 1
                            Layout.leftMargin: 20
                            Layout.rightMargin: 20
                            Layout.topMargin: 10
                            Layout.bottomMargin: 10
                            color: Qt.rgba(255, 255, 255, 0.1)
                        }
                        
                        // 菜单项：系统设置
                        NavMenuItem {
                            icon: "⚙️"
                            text: "系统设置"
                            pageId: "settings"
                            active: currentPage === "settings"
                            onClicked: switchToPage("settings")
                        }
                        
                        Item { Layout.fillHeight: true } // 占位
                    }
                }
                
                // 底部状态栏
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 60
                    color: Qt.rgba(0, 0, 0, 0.2)
                    
                    RowLayout {
                        anchors.fill: parent
                        anchors.margins: 15
                        spacing: 10
                        
                        Rectangle {
                            width: 8
                            height: 8
                            radius: 4
                            color: "#10b981"
                            
                            SequentialAnimation on opacity {
                                running: true
                                loops: Animation.Infinite
                                NumberAnimation { from: 1.0; to: 0.3; duration: 1000 }
                                NumberAnimation { from: 0.3; to: 1.0; duration: 1000 }
                            }
                        }
                        
                        Column {
                            Layout.fillWidth: true
                            spacing: 2
                            
                            Text {
                                text: "系统运行中"
                                font.pixelSize: 12
                                color: "white"
                            }
                            
                            Text {
                                text: "设备: " + deviceModel.count + " 台"
                                font.pixelSize: 10
                                color: Qt.rgba(255, 255, 255, 0.6)
                            }
                        }
                    }
                }
            }
        }
        
        // ========================================
        // 右侧主内容区
        // ========================================
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: backgroundColor
            
            ColumnLayout {
                anchors.fill: parent
                spacing: 0
                
                // 顶部工具栏
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 60
                    color: "white"
                    
                    // 阴影效果
                    layer.enabled: true
                    layer.effect: DropShadow {
                        horizontalOffset: 0
                        verticalOffset: 2
                        radius: 8
                        samples: 16
                        color: Qt.rgba(0, 0, 0, 0.05)
                    }
                    
                    RowLayout {
                        anchors.fill: parent
                        anchors.leftMargin: 20
                        anchors.rightMargin: 20
                        
                        // 菜单切换按钮
                        Button {
                            text: drawerOpen ? "☰" : "☰"
                            font.pixelSize: 20
                            flat: true
                            onClicked: drawerOpen = !drawerOpen
                            
                            ToolTip.visible: hovered
                            ToolTip.text: drawerOpen ? "收起侧边栏" : "展开侧边栏"
                        }
                        
                        // 页面标题
                        Text {
                            text: getPageTitle()
                            font.pixelSize: 20
                            font.bold: true
                            color: "#333"
                        }
                        
                        Item { Layout.fillWidth: true }
                        
                        // 工具栏按钮
                        Button {
                            text: "刷新"
                            flat: true
                            onClicked: {
                                console.log("刷新当前页面")
                                refreshCurrentPage()
                            }
                        }
                        
                        Button {
                            text: "关于"
                            flat: true
                            onClicked: {
                                aboutDialog.showInfo(
                                    "Modbus TCP 监控系统 v1.0.0",
                                    "工业设备实时监控与数据采集系统\n\n© 2025 IndustrialMonitor"
                                )
                            }
                        }
                    }
                }
                
                // 主内容区（StackLayout 实现页面切换）
                StackLayout {
                    id: stackLayout
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    currentIndex: getPageIndex(currentPage)
                    
                    // 页面 0：仪表盘
                    Pages.DashboardPage {
                        id: dashboardPage
                    }
                    
                    // 页面 1：设备管理
                    Pages.DeviceManagePage {
                        id: deviceManagePage
                    }
                    
                    // 页面 2：历史数据
                    Pages.HistoryPage {
                        id: historyPage
                    }
                    
                    // 页面 3：报警管理
                    Pages.AlarmPage {
                        id: alarmPage
                    }
                    
                    // 页面 4：系统设置
                    Pages.SettingsPage {
                        id: settingsPage
                    }
                }
            }
        }
    }
    
    // ========================================
    // 自定义导航菜单项组件
    // ========================================
    component NavMenuItem: Rectangle {
        property string icon: ""
        property string text: ""
        property string pageId: ""
        property bool active: false
        
        signal clicked()
        
        Layout.fillWidth: true
        Layout.preferredHeight: 50
        Layout.leftMargin: 15
        Layout.rightMargin: 15
        
        radius: 8
        color: active ? primaryColor : (mouseArea.containsMouse ? Qt.rgba(255, 255, 255, 0.1) : "transparent")
        
        Behavior on color {
            ColorAnimation { duration: 200 }
        }
        
        RowLayout {
            anchors.fill: parent
            anchors.leftMargin: 15
            anchors.rightMargin: 15
            spacing: 15
            
            Text {
                text: parent.parent.icon
                font.pixelSize: 20
                color: "white"
            }
            
            Text {
                text: parent.parent.text
                font.pixelSize: 15
                color: "white"
                Layout.fillWidth: true
            }
        }
        
        MouseArea {
            id: mouseArea
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: Qt.PointingHandCursor
            onClicked: parent.clicked()
        }
    }
    
    // ========================================
    // DropShadow 效果（需要导入 Qt5Compat.GraphicalEffects）
    // ========================================
    component DropShadow: Item {
        property real horizontalOffset: 0
        property real verticalOffset: 0
        property real radius: 8
        property int samples: 16
        property color color: "black"
        
        // 简化版阴影效果（实际项目中使用 Qt5Compat.GraphicalEffects）
    }
    
    // ========================================
    // JavaScript 函数
    // ========================================
    
    // 切换页面
    function switchToPage(pageId) {
        console.log("切换到页面:", pageId)
        currentPage = pageId
    }
    
    // 获取页面索引
    function getPageIndex(pageId) {
        switch(pageId) {
            case "dashboard": return 0
            case "device": return 1
            case "history": return 2
            case "alarm": return 3
            case "settings": return 4
            default: return 0
        }
    }
    
    // 获取页面标题
    function getPageTitle() {
        switch(currentPage) {
            case "dashboard": return "📊 仪表盘"
            case "device": return "⚙️ 设备管理"
            case "history": return "📈 历史数据"
            case "alarm": return "🚨 报警管理"
            case "settings": return "⚙️ 系统设置"
            default: return "Modbus TCP 监控系统"
        }
    }
    
    // 刷新当前页面
    function refreshCurrentPage() {
        switch(currentPage) {
            case "dashboard":
                console.log("刷新仪表盘数据")
                // dataController.refreshRealtimeData()
                break
            case "device":
                console.log("刷新设备列表")
                deviceModel.loadFromDatabase()
                break
            case "history":
                console.log("刷新历史数据")
                // historyModel.refresh()
                break
            case "alarm":
                console.log("刷新报警列表")
                // alarmModel.refresh()
                break
            case "settings":
                console.log("刷新系统设置")
                break
        }
    }
    
    // ========================================
    // 通用确认对话框（全局使用）
    // ========================================
    ConfirmDialog {
        id: confirmDialog
        parent: Overlay.overlay
    }
    
    // 关于对话框
    ConfirmDialog {
        id: aboutDialog
        parent: Overlay.overlay
    }
    
    // ========================================
    // 组件加载完成
    // ========================================
    Component.onCompleted: {
        console.log("==============================================")
        console.log("✅ Main.qml 主界面加载完成")
        console.log("==============================================")
        console.log("📋 系统信息:")
        console.log("  - 窗口大小:", width, "x", height)
        console.log("  - 设备数量:", deviceModel.count)
        console.log("  - 当前页面:", currentPage)
        console.log("==============================================")
        
        // 测试 Controller 通信
        console.log("🔧 测试 C++ 与 QML 通信:")
        console.log("  - modbusController:", modbusController !== undefined ? "✓" : "✗")
        console.log("  - dataController:", dataController !== undefined ? "✓" : "✗")
        console.log("  - alarmController:", alarmController !== undefined ? "✓" : "✗")
        console.log("  - settingsController:", settingsController !== undefined ? "✓" : "✗")
        console.log("  - deviceModel:", deviceModel !== undefined ? "✓" : "✗")
        console.log("  - dataRecordModel:", dataRecordModel !== undefined ? "✓" : "✗")
        console.log("  - historyModel:", historyModel !== undefined ? "✓" : "✗")
        console.log("  - alarmModel:", alarmModel !== undefined ? "✓" : "✗")
        console.log("==============================================")
    }
}
